#include "core.h"

CErrorLog::CErrorLog()
{

}

CErrorLog::~CErrorLog()
{

}

CErrorLog* CErrorLog::getInstance()
{
	static CErrorLog *p = NULL;
	if (!p)
	{
		p = new CErrorLog;
	}
	return p;
}

bool CErrorLog::Initialize(std::string host)
{
	m_strUrl = "http://";
	m_strUrl += host;
	m_strUrl += "/index/error";
	return true;
}

bool CErrorLog::Destory()
{
	delete this;
	return true;
}

STErrorLogResponse* CErrorLog::errorLog(STErrorLogRequest *pRequest, std::string method)
{
	std::string requestUrl = m_strUrl;
	requestUrl += "/";
	requestUrl += pRequest->appname;
	m_mapRequestParameter = mapRequestParameter;
	m_vecRequestParameter = vecRequestParameter;
	addQuerryParameter("page", pRequest->page, m_mapRequestParameter, m_vecRequestParameter);
	addQuerryParameter("page_size", pRequest->page_size, m_mapRequestParameter, m_vecRequestParameter);
	addQuerryParameter("sort_mode", pRequest->sort_mode, m_mapRequestParameter, m_vecRequestParameter);

	std::string strtmp = "";
	if (!Request(requestUrl, method, GetQuerryParameter(m_mapRequestParameter, m_vecRequestParameter, method, strtmp)))
	{
		printf("[%s]:%d\n", __FUNCTION__, __LINE__);
		return NULL;
	}

	parseerrorLogResponse();
	return &m_errorLogResponse;
}

bool CErrorLog::parseerrorLogResponse()
{
	Json::Reader reader;
	Json::Value result;
	printf("%s\n", g_buf_tmp.data);
	if (reader.parse(g_buf_tmp.data, result))
	{
		m_errorLogResponse.status = result["status"].asString();
		if (m_errorLogResponse.status == "OK")
		{
			Json::Value result2 = result["result"];
			m_errorLogResponse.page = result2["page"].asUInt();
			m_errorLogResponse.page_size = result2["page_size"].asString();
			uint32_t count = result2["items"].size();
			for (uint32_t i=0; i<count; i++)
			{
				STErrorItemInfo errorItemInfo;
				errorItemInfo.cmd = result2["items"][i]["cmd"].asString();
				errorItemInfo.fields = result2["items"][i]["fields"].asString();
				errorItemInfo.error_code = result2["items"][i]["error_code"].asUInt();
				errorItemInfo.error_message = result2["items"][i]["error_message"].asString();
				m_errorLogResponse.items.push_back(errorItemInfo);
			}
		}
		else
		{
			uint32_t count = result["errors"].size();
			Json::Value errors = result["errors"];
			for (uint32_t i=0; i<count; i++)
			{
				STErrorInfo errorInfo;
				errorInfo.errorCode = errors[i]["code"].asUInt();
				errorInfo.errorMessage = errors[i]["message"].asString();
				m_errorLogResponse.errorList.push_back(errorInfo);
			}
		}
		m_errorLogResponse.request_id = result["request_id"].asString();
	}
	return true;
}